package nil.ed.simulator.request.biz.qq.listener;

import nil.ed.simulator.request.common.NamedValue;
import nil.ed.simulator.request.common.QQItem;
import nil.ed.simulator.request.enums.events.EventType;
import nil.ed.simulator.request.event.Event;
import nil.ed.simulator.request.event.bus.EventListener;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lidelin.
 */
public class CookieStoreEventListener implements EventListener {
    @Override
    public void onEvent(Event event) {
        List<NamedValue> namedValues = null;
        if (event.getData() instanceof java.net.CookieStore) {
            namedValues = ((java.net.CookieStore) (event.getData())).getCookies().stream().map(c -> NamedValue.builder()
                    .name(c.getName())
                    .value(c.getValue())
                    .build()).collect(Collectors.toList());
        } else if (event.getData() instanceof org.apache.http.client.CookieStore) {
            namedValues = ((org.apache.http.client.CookieStore) (event.getData())).getCookies().stream().map(c -> NamedValue.builder()
                    .name(c.getName())
                    .value(c.getValue())
                    .build()).collect(Collectors.toList());
        }
        Map<String, Object> extendMap = event.getExtendMap();
        QQItem qqItem = (QQItem) extendMap.get("entity");
        if (namedValues != null) {
            qqItem.setCookies(namedValues);
        }
    }

    @Override
    public boolean isSupport(Event event) {
        return event.getEventType() == EventType.COOKIE_STORE;
    }
}
